package com.lyrcsoft;

import java.io.*;
import java.nio.charset.StandardCharsets;

/**
 * @author fujc-dev@qq.com
 * @date 2023/8/1 10:38
 */

public class ByteArrayInputStreamExample {

    public static void main(String[] args) {
        byte[] bytes = { 72, 101, 108, 108, 111, 32, 87, 111, 114, 108, 100, 33 };
        // 创建字节输入流对象
        ByteArrayInputStream basis = new ByteArrayInputStream(bytes);
        try {
            byte[] buffer = new byte[1024];
            int len;
            // 使用 while 循环读取字节数组中的内容，每次最多读取 1024 个字节
            while ((len = basis.read(buffer)) != -1) {
                // 将读取的字节转换为字符串，并输出到控制台
                String content = new String(buffer, 0, len, StandardCharsets.UTF_8);
                System.out.println(content);
            }
        } catch (IOException e) {
            System.out.println("Error reading byte array: " + e.getMessage());
        } finally {
            // 关闭输入流
            try {
                basis.close();
            } catch (IOException e) {
                System.out.println("Error closing byte array input stream: " + e.getMessage());
            }
        }
    }
}